package example.servlet;

import example.pojo.Supplier;
import example.service.StorageRecordService;
import example.service.StorageRecordServiceImpl;
import example.service.SupplierService;
import example.service.SupplierServiceImpl;
import example.util.Page;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@MultipartConfig(maxFileSize = 1024 * 1024 * 1)
@WebServlet(urlPatterns = "/supplier")
public class SupplierServlet extends HttpServlet {

    /**
     * 接收初始化参数
     */
    private String uploadPath;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        //获取全局初始化参数
        uploadPath = this.getServletContext().getInitParameter("uploadPath");
        System.out.println("全局初始化参数: uploadPath=" + uploadPath);
    }

    private SupplierService supplierService = new SupplierServiceImpl();
    private StorageRecordService recordService = new StorageRecordServiceImpl();
    private PrintWriter out;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //编码方式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        out = resp.getWriter();
        String opr = req.getParameter("opr");
        if (opr.equals("list")) {
            list(req, resp);
        } else if (opr.equals("toAdd")) {
            req.getRequestDispatcher("/WEB-INF/jsp/supplier/add.jsp").forward(req, resp);
        } else if (opr.equals("add")) {
            add(req, resp);
        } else if (opr.equals("view")) {
            view(req, resp);
        } else if (opr.equals("toUpdate")) {
            int supId = Integer.parseInt(req.getParameter("supId"));
            Supplier supplier = supplierService.view(supId);
            req.setAttribute("supplier", supplier);
            req.getRequestDispatcher("/WEB-INF/jsp/supplier/update.jsp").forward(req, resp);
        } else if (opr.equals("update")) {
            update(req, resp);
        }else if(opr.equals("del")){
            del(req,resp);
        }
    }

    private void del(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //删除供货商 判断是否有入库记录
        out = resp.getWriter();
        int supId = Integer.parseInt(req.getParameter("supId"));
        //获取指定供货商的入库信息
        int recordCount = recordService.getRByS(supId);
        if(recordCount > 0){
            System.out.println("该供货商有入库信息");
            out.println(recordCount);
        }else if(supplierService.del(supId) > 0){
            System.out.println("供货商信息删除成功");
            out.println("true");
        }else{
            System.out.println("供货商信息删除成功");
            out.println("false");
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Supplier supplier = new Supplier();
        //获取参数
        int id = Integer.parseInt(req.getParameter("id"));
        supplier.setId(id);
        String supCode = req.getParameter("supCode");
        supplier.setSupCode(supCode);
        String supName = req.getParameter("supName");
        supplier.setSupName(supName);
        String supDesc = req.getParameter("supDesc");
        supplier.setSupDesc(supDesc);
        String supContact = req.getParameter("supContact");
        supplier.setSupContact(supContact);
        String supPhone = req.getParameter("supPhone");
        supplier.setSupPhone(supPhone);
        String supAddress = req.getParameter("supAddress");
        supplier.setSupAddress(supAddress);
        String supFax = req.getParameter("supFax");
        supplier.setSupFax(supFax);

        if (supplierService.upd(supplier) > 0) {
            System.out.println("供货商数据修改成功");
            req.getRequestDispatcher("supplier?opr=list&pageIndex=1").forward(req, resp);
        } else {
            System.out.println("供货商数据修改失败");
            req.getRequestDispatcher("/WEB-INF/jsp/supplier/list.jsp").forward(req, resp);
        }
    }

    private void  view(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int supId = Integer.parseInt(req.getParameter("supId"));
        Supplier supplier = supplierService.view(supId);
        req.setAttribute("supplier", supplier);
        req.getRequestDispatcher("/WEB-INF/jsp/supplier/view.jsp").forward(req, resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        if (ServletFileUpload.isMultipartContent(req)) {
            Supplier supplier = new Supplier();
            //获取参数
            String supCode = req.getParameter("supCode");
            supplier.setSupCode(supCode);
            String supName = req.getParameter("supName");
            supplier.setSupName(supName);
            String supDesc = req.getParameter("supDesc");
            supplier.setSupDesc(supDesc);
            String supContact = req.getParameter("supContact");
            supplier.setSupContact(supContact);
            String supPhone = req.getParameter("supPhone");
            supplier.setSupPhone(supPhone);
            String supAddress = req.getParameter("supAddress");
            supplier.setSupAddress(supAddress);
            String supFax = req.getParameter("supFax");
            supplier.setSupFax(supFax);

            //获取文件
            Part companyLicPicPathPart = req.getPart("companyLicPic");
            Part orgCodePicPathPart = req.getPart("orgCodePic");

            //获取文件名
            String companyLicPicPathFileName = extractFileName(companyLicPicPathPart);
            String orgCodePicPathFileName = extractFileName(orgCodePicPathPart);

            //将文件写入磁盘
            companyLicPicPathPart.write("E:\\S3\\ssm\\ch04\\src\\main\\webapp\\statics\\upload" + File.separator + companyLicPicPathFileName);
            orgCodePicPathPart.write("E:\\S3\\ssm\\ch04\\src\\main\\webapp\\statics\\upload" + File.separator + orgCodePicPathFileName);
            System.out.println("企业营业执照上传成功：" + companyLicPicPathFileName);
            supplier.setCompanyLicPicPath(uploadPath + "/" + companyLicPicPathFileName);

            System.out.println("组织机构代码证上传成功：" + orgCodePicPathFileName);
            supplier.setOrgCodePicPath(uploadPath + "/" + orgCodePicPathFileName);

            if (supplierService.add(supplier) > 0) {
                System.out.println("供货商数据添加成功");
                req.getRequestDispatcher("supplier?opr=list&pageIndex=1").forward(req, resp);
            } else {
                System.out.println("供货商数据添加失败");
                req.getRequestDispatcher("/WEB-INF/jsp/supplier/list.jsp").forward(req, resp);
            }
        }

    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageIndex = Integer.parseInt(req.getParameter("pageIndex"));
        String querySupCode = req.getParameter("querySupCode");
        String querySupName = req.getParameter("querySupName");
        Page<Supplier> supplierPage = new Page<Supplier>();
        //设置总数据量
        supplierPage.setTotalPage(supplierService.count(querySupCode, querySupName));
        //设置总页数
        supplierPage.setTotalPageSize();
        //当前页
        supplierPage.setPageIndex(pageIndex);
        //获取当前页数据
        supplierPage.setList(supplierService.select(querySupCode, querySupName, supplierPage.getPageIndex(), supplierPage.getPageSize()));
        //数据回显
        req.setAttribute("querySupCode", querySupCode);
        req.setAttribute("querySupName", querySupName);
        req.setAttribute("supplierList", supplierPage.getList());
        req.setAttribute("totalPageCount", supplierPage.getTotalPageSize());
        req.setAttribute("totalCount", supplierPage.getTotalPage());
        req.setAttribute("currentPageNo", supplierPage.getPageIndex());
        req.getRequestDispatcher("/WEB-INF/jsp/supplier/list.jsp").forward(req, resp);
    }

    /**
     * 获取上传的文件名
     */
    private String extractFileName(Part part) {
        String fileName = "";
        String contentDisp = part.getHeader("content-disposition");
        //使用；分割字符串
        String[] items = contentDisp.split(";");
        for (String s : items) {
            //指定前缀开头的字符串
            if (s.trim().startsWith("filename")) {
                return fileName = s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        return "";
    }
}
